<?php
class Base_Controller extends CI_Controller
{
//    public $api_base_url = "http://localhost:8888/nldou_api/";
//    public $wap_base_url = "http://localhost:8888/nldou_wap/";
//    public $web_base_url = "http://localhost:8888/nldou_web/";
    public $api_base_url = "http://api.nldou.com/";
    public $wap_base_url = "http://wap.nldou.com/";
    public $web_base_url = "http://www.nldou.com/";
    public $_uid;//后台管理员ID
    public $_commid;//后台管理员普通用户ID
    public $_utype;
    public $_page_size;
    public $_external_id = 0;//配置表在form_config中的ID
    public $_form_type;//配置表的类型
    public $_form_table;//配置表
    public $_form_table_pkey;//配置表的主键
    public $_list_where;//配置表的列表条件
    public $_action_list;//配置表的列表操作项
    public $_controller;//配置表的控制器
    public $_list_sort_key;
    public $_list_sort_type;
    public $_update_data;
    public $_create_data;
    public $_resource_url;
    public $_media_url;

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->_resource_url = $this->config->item('resource_url');
        $this->_media_url = $this->config->item('media_url');
        //后台管理控制器
        if ($this->uri->segment(1,0) == 'admin'){
            $this->load->model('adminuser_model');
            $this->load->model('adminform_model');
            //登陆验证
            $this->checkAdminLogin();
            //设定表格
            $this->setFormtable();
        }
    }
    /**
     * 后台管理|登陆控制
     */
    private function checkAdminLogin()
    {
        if (!isset($_SESSION)) session_start();
        if(isset($_SESSION['uid'])&&isset($_SESSION['utype'])){
            $this->_uid = (int)$_SESSION['uid'];
            $this->_utype = $_SESSION['utype'];
            if ($this->uri->segment(2,0) == 'adminlogin'){
                redirect('/admin/adminmain/');
                exit;
            }
        }else{
            //不是登陆页面跳转登陆页面
            if ($this->uri->segment(2,0) != 'adminlogin'){
                redirect('/admin/adminlogin/');
                exit;
            }
        }

    }
    /**
     * 后台管理|生成视图
     * 视图主内容
     */
    public function getAdminView($content='',$myjspath='')
    {
        //header html
        $hdata = array(
            'cssroot'=>base_url('html/admin/css/'),
            'jsroot'=>base_url('html/admin/js/'),
            'myjspath'=>$myjspath
        );
        $header = $this->load->view('admin/header',$hdata,true);
        //navbar html
        if (empty($this->_uid)) {redirect('/admin/adminlogin/');exit();}
        $user = $this->adminuser_model->getUser($this->_uid);
        $ndata = array('username'=>$user['userName'],'userIcon'=>"http://wap.nldou.com".$user['userIcon'],
            'imgroot'=>base_url('html/admin/img/'),'logout'=>site_url('admin/adminmain/logout'));
        $navbar = $this->load->view('admin/navbar',$ndata,true);
        //sidebar html
        $sdata = $this->adminform_model->getMenus($user['privilege']);
        $sidebar = $this->load->view('admin/sidebar',$sdata,true);
        //admin view html
        $mdata = array(
            'header'=>$header,
            'navbar'=>$navbar,
            'sidebar'=>$sidebar,
            'content'=>$content
        );
        return $this->load->view('admin/main',$mdata,true);
    }

    /**
     * 后台管理|设定配置表
     */
    public function setFormtable()
    {
        $res = $this->adminform_model->getTable($this->_form_type);
        $this->_form_table = $res['tablename'];
        $this->_form_table_pkey = $res['pkey'];
        $this->_list_sort_key = $res['list_sort_key'];
        $this->_list_sort_type = $res['list_sort_type'];
    }
    /**
     * 后台管理|生成视图分页
     * 配置表控制器和方法
     */
    public function getPagination($uri)
    {
        $total = $this->adminform_model->getPageTotalNum($this->_form_table,$this->_list_where);
        $this->load->library('pagination');

        $config['base_url'] = site_url($uri);
        $config['total_rows'] = $total;
        $config['per_page'] = $this->_page_size;
        $config['cur_tag_open'] = '<div class="cur-page">';
        $config['cur_tag_close'] = '</div>';
        $config['use_page_numbers'] = TRUE;
        $config['num_tag_open'] = '<div class="pageitem">';
        $config['num_tag_close'] = '</div>';
        $config['prev_link'] = '上一页';
        $config['prev_tag_open'] = '<div class="pre-page">';
        $config['prev_tag_close'] = '</div>';
        $config['next_link'] = '下一页';
        $config['next_tag_open'] = '<div class="next-page">';
        $config['next_tag_close'] = '</div>';
        $config['last_link'] = '最后一页';
        $config['last_tag_open'] = '<div class="last-page">';
        $config['last_tag_close'] = '</div>';
        $config['first_link'] = '第一页';
        $config['first_tag_open'] = '<div class="first-page">';
        $config['first_tag_close'] = '</div>';
        $config['full_tag_open'] = '<div class="page-total-results">共'.$total.'条，每页'.$this->_page_size.'条</div>';

        $this->pagination->initialize($config);

        return array('total'=>$total,'pagination'=>$this->pagination->create_links());
    }
    /**
     * 后台管理|生成列表
     * 分页参数
     */
    public function getList($offset = 0,$limit = 0)
    {
        return $this->adminform_model->getList($this->_form_type,$this->_form_table,$this->_list_where,
            $offset,$limit,$this->_action_list,$this->_controller,$this->_form_table_pkey,$this->_external_id,
            $this->_list_sort_key,$this->_list_sort_type);
    }
    /**
     * 后台管理|生成配置表的数据创建页
     */
    public function createBuildForm()
    {
        return $this->adminform_model->createBuildForm($this->_form_type);
    }
    /**
     * 后台管理|插入配置表的新创建的数据
     * 新创建的数据
     */
    public function create()
    {
        $id = $this->adminform_model->create($this->_form_table,$this->_create_data);
        if (!empty($id)) $this->aftercreate($id);
        $red = empty($this->_external_id)?'showlist/1':'showlist/'.$this->_external_id.'/1';
        redirect(site_url($this->_controller).$red);

    }
    public function aftercreate($id){}
    /**
     * 后台管理|生成配置表的数据更新页
     */
    public function updateBuildForm($pkeyval)
    {
        return $this->adminform_model->updateBuildForm($this->_form_type,$this->_form_table,$this->_form_table_pkey,$pkeyval);
    }
    /**
     * 后台管理|插入配置表的新创建的数据
     * 要更新的数据
     * 更新项的主键值
     */
    public function update($pkeyval)
    {
        $this->adminform_model->update($this->_form_table,$this->_update_data,$this->_form_table_pkey,$pkeyval);
        $this->afterupdate($this->_form_table_pkey,$pkeyval);
        $red = empty($this->_external_id)?'showlist/1':'showlist/'.$this->_external_id.'/1';
        redirect(site_url($this->_controller).$red);
    }
    public function afterupdate($pkey,$pkeyval){}
    /**
     * 后台管理|删除配置表的数据
     * 删除项的主键值
     */
    public function delete($pkeyval)
    {
        $this->adminform_model->deleteData($this->_form_table,array($this->_form_table_pkey=>$pkeyval));
        $this->afterdelete($this->_form_table_pkey,$pkeyval);
        $red = empty($this->_external_id)?'showlist/1':'showlist/'.$this->_external_id.'/1';
        redirect(site_url($this->_controller).$red);
    }
    public function afterdelete($pkey,$pkeyval){}
    /**
     * 获取验证码
     */
    public function getCaptcha()
    {
        $this->load->helper('captcha');
        $this->config->load('captcha');

        $imgurl  = $this->config->item('img_url');
        $imgpath = $this->config->item('img_path');
        $imgw    = $this->config->item('img_width');
        $imgh    = $this->config->item('img_height');
        $exp     = $this->config->item('expiration');
        $wl      = $this->config->item('word_length');
        $fontsize= $this->config->item('font_size');
        $font    = $this->config->item('font_path');

        $config = array(
            'img_url'=>$imgurl,
            'img_path'=>$imgpath,
            'img_width'=>$imgw,
            'img_height'=>$imgh,
            'expiration'=>$exp,
            'word_length'=>$wl,
            'font_size'=>$fontsize,
            'font_path'=>$font
        );
        $cap = create_captcha($config);

        $res = $this->saveCaptcha($cap['word']);

        if ($res){
            return $cap['image'];
        } else {
            $this->error('系统错误，请重试');
        }
    }
    /**
     * 存入验证码
     */
    public function saveCaptcha($cap)
    {
        $this->load->database();
        $data = array('ip'=>$this->input->ip_address(),'captcha'=>$cap,'created'=>time());
        $res = $this->db->insert('common_captcha',$data);
        return $res;

    }

    protected function formatImgurl($img='')
    {
        return empty($img) ? '' : $this->api_base_url.$img;
    }
    
    protected function success($data=array(),$msg = "sucess"){
        $result['code'] = 1;
        $result['msg'] = (string)$msg;
        $result['data'] = empty($data)?(object)array():$data;
        $this->echoJsonData($result);
        exit;
    }


    protected function error($msg = 'error',$data='') {
        $result ['code'] = 0;
        $result ['msg'] = (string)$msg;
        $result ['data'] = empty($data)?(object)array():$data;
        $this->echoJsonData($result);
        exit;
    }

    /**
     * 输出json数据
     * @param  array $data
     * @return void
     */
    protected function echoJsonData($data){
    	//header("Access-Control-Allow-Origin:".$this->wap_base_url);
    	//header("Access-Control-Allow-Credentials:true");
        echo json_encode($data);
    }

    /**
     * 过滤输出json数据
     * @param  array|string|int $data
     * @return string|int
     */
    protected function filterJsonData($data){
        if($data === null){
            return '';
        }
        elseif (empty($data)) {
            return $data;
        } else {
            return is_array($data) ? array_map('', $data) : ($data === null ? '' : $data);
        }
    }

    public function uploadImg($imagename,$width=0,$height=0,$maintainRatio = true)
    {
        $upload_db_path = '/upload/images/'.date('Ymd',time()).'/';
        $uploadpath = '/home/nldou/webroot/wap'.$upload_db_path;
        if(!file_exists($uploadpath)){
            mkdir($uploadpath,0777,true);
        }
        $config['upload_path'] = $uploadpath;
        $config['allowed_types']='gif|jpg|png';

        $file_arr = array();
        $imgurl = array();
        if(isset($_FILES[$imagename])&&!empty($_FILES[$imagename])){
            if (is_array($_FILES[$imagename]['name'])) {
                $cou=count($_FILES[$imagename]['name']);
                for($i = 0; $i < $cou ;$i++){
                    if (empty($_FILES[$imagename]['name'][$i])) continue;
                    $file_arr[$i]['name'] = $_FILES[$imagename]['name'][$i];
                    $file_arr[$i]['type'] = $_FILES[$imagename]['type'][$i];
                    $file_arr[$i]['tmp_name'] = $_FILES[$imagename]['tmp_name'][$i];
                    $file_arr[$i]['error'] = $_FILES[$imagename]['error'][$i];
                    $file_arr[$i]['size'] = $_FILES[$imagename]['size'][$i];
                }
            } else {
                $file_arr[0]['name'] = $_FILES[$imagename]['name'];
                $file_arr[0]['type'] = $_FILES[$imagename]['type'];
                $file_arr[0]['tmp_name'] = $_FILES[$imagename]['tmp_name'];
                $file_arr[0]['error'] = $_FILES[$imagename]['error'];
                $file_arr[0]['size'] = $_FILES[$imagename]['size'];
            }
            if (empty($file_arr)) return array('code'=>0,'imgurl'=>array());
            $this->load->library('Myupload');
            $this->myupload->setConfig($config);

            $this->load->library('image_lib');
            if ($width>0) $config2['width'] = $width;
            if ($height>0) $config2['height'] = $height;
            $config2['maintain_ratio'] = $maintainRatio;
            foreach($file_arr as $k => $v) {
                $_FILES[$imagename] = $v;
                $identityRes = $this->myupload->doUpload($imagename);
                if ($identityRes['code']) {
                    $imgurl[] = $upload_db_path.$identityRes['data']['upload_data']['file_name'];
                    //处理图片
                    if ($identityRes['data']['upload_data']['image_type']!='gif'){
                        $config2['source_image'] = $uploadpath.$identityRes['data']['upload_data']['file_name'];
                        $this->image_lib->initialize($config2);
                        if (!$this->image_lib->resize())
                        {
                            echo $this->image_lib->display_errors();
                            exit();
                        }
                        $this->image_lib->clear();
                    }
                } else {
                    return array('code'=>0,'msg'=>$identityRes['data']['error']);
                }
            }
        }else{return array('code'=>0,'imgurl'=>array());}

        return array('code'=>1,'imgurl'=>$imgurl);
    }

    public function uploadfiles($filename)
    {
        $upload_db_path = '/upload/images/'.date('Ymd',time()).'/';
        $uploadpath = '/home/nldou/webroot/wap'.$upload_db_path;
        if(!file_exists($uploadpath)){
            mkdir($uploadpath,0777,true);
        }
        $config['upload_path'] = $uploadpath;
        $config['allowed_types']='xlsx|csv';
        $config['encrypt_name']=false;

        $file_arr = array();
        $fileurl = array();
        if(isset($_FILES[$filename])&&!empty($_FILES[$filename])){
            $cou=count($_FILES[$filename]['name']);
            for($i = 0; $i < $cou ;$i++){
                if (empty($_FILES[$filename]['name'][$i])) continue;
                $file_arr[$i]['name'] = $_FILES[$filename]['name'][$i];
                $file_arr[$i]['type'] = $_FILES[$filename]['type'][$i];
                $file_arr[$i]['tmp_name'] = $_FILES[$filename]['tmp_name'][$i];
                $file_arr[$i]['error'] = $_FILES[$filename]['error'][$i];
                $file_arr[$i]['size'] = $_FILES[$filename]['size'][$i];
            }
            if (empty($file_arr)) return array('code'=>0,'fileurl'=>array());
            $this->load->library('Myupload');
            $this->myupload->setConfig($config);

            foreach($file_arr as $k => $v) {
                $_FILES[$filename] = $v;
                $identityRes = $this->myupload->doUpload($filename);
                if ($identityRes['code']) {
                    $fileurl[] = $upload_db_path.$identityRes['data']['upload_data']['file_name'];
                } else {
                    return array('code'=>0,'msg'=>$identityRes['data']['error']);
                }
            }
        }else{return array('code'=>0,'fileurl'=>array());}

        return array('code'=>1,'fileurl'=>$fileurl);
    }

    public function uploadvoice($voicename)
    {
        $upload_db_path = '/voice/'.date('Ymd',time()).'/';
        $uploadpath = '/home/nldou/webroot/media'.$upload_db_path;
        if(!file_exists($uploadpath)){
            mkdir($uploadpath,0777,true);
        }
        $config['upload_path'] = $uploadpath;
        $config['allowed_types']='mp3|wav';

        $file_arr = array();
        $voiceurl = array();
        if(isset($_FILES[$voicename])&&!empty($_FILES[$voicename])){
            $cou=count($_FILES[$voicename]['name']);
            for($i = 0; $i < $cou ;$i++){
                if (empty($_FILES[$voicename]['name'][$i])) continue;
                $file_arr[$i]['name'] = $_FILES[$voicename]['name'][$i];
                $file_arr[$i]['type'] = $_FILES[$voicename]['type'][$i];
                $file_arr[$i]['tmp_name'] = $_FILES[$voicename]['tmp_name'][$i];
                $file_arr[$i]['error'] = $_FILES[$voicename]['error'][$i];
                $file_arr[$i]['size'] = $_FILES[$voicename]['size'][$i];
            }
            if (empty($file_arr)) return array('code'=>0,'voiceurl'=>array());
            $this->load->library('Myupload');
            $this->myupload->setConfig($config);
            foreach($file_arr as $k => $v) {
                $_FILES[$voicename] = $v;
                $identityRes = $this->myupload->doUpload($voicename);
                if ($identityRes['code']) {
                    $voiceurl[] = $upload_db_path.$identityRes['data']['upload_data']['file_name'];
                } else {
                    return array('code'=>0,'msg'=>$identityRes['data']['error']);
                }
            }
        }else{return array('code'=>0,'voiceurl'=>array());}

        return array('code'=>1,'voiceurl'=>$voiceurl);
    }
}
